package cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon.config;

import cn.iocoder.yudao.framework.tenant.core.util.TenantUtils;
import cn.iocoder.yudao.module.crossborder.platform.dal.dataobject.platformconfig.PlatformConfigDO;
import cn.iocoder.yudao.module.crossborder.platform.service.platformconfig.PlatformConfigService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * Amazon平台配置管理
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class AmazonPlatformConfig {

    @Resource
    private PlatformConfigService platformConfigService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    private static final String AMAZON_PLATFORM_CODE = "amazon";

    // 配置缓存
    private volatile PlatformConfigDO cachedConfig;
    private volatile long lastCacheTime = 0;
    private static final long CACHE_EXPIRE_TIME = 300000; // 5分钟缓存

    // 默认配置
    @Value("${amazon.platform.enabled:true}")
    private Boolean defaultEnabled;

    @Value("${amazon.platform.api-version:v0}")
    private String defaultApiVersion;

    @Value("${amazon.platform.timeout:30}")
    private Integer defaultTimeout;

    /**
     * 初始化Amazon平台配置
     */
    @PostConstruct
    public void initAmazonConfig() {
        log.info("初始化Amazon平台配置");

        try {
            // 注意：忽略自动多租户，因为要全局初始化配置
            TenantUtils.executeIgnore(() -> {
                // 检查是否已存在Amazon平台配置
                PlatformConfigDO existingConfig = platformConfigService.getPlatformConfigByCode(AMAZON_PLATFORM_CODE);
                if (existingConfig == null) {
                    log.info("Amazon平台配置不存在，创建默认配置");
                    createDefaultAmazonConfig();
                } else {
                    log.info("Amazon平台配置已存在，ID: {}", existingConfig.getId());
                    cachedConfig = existingConfig;
                    lastCacheTime = System.currentTimeMillis();
                }
            });
        } catch (Exception e) {
            log.error("初始化Amazon平台配置失败", e);
        }
    }

    /**
     * 获取Amazon平台配置（带缓存）
     *
     * @return Amazon平台配置
     */
    public PlatformConfigDO getAmazonConfig() {
        // 检查缓存是否过期
        if (cachedConfig == null || (System.currentTimeMillis() - lastCacheTime) > CACHE_EXPIRE_TIME) {
            synchronized (this) {
                if (cachedConfig == null || (System.currentTimeMillis() - lastCacheTime) > CACHE_EXPIRE_TIME) {
                    // 注意：忽略自动多租户，因为要全局查询配置
                    cachedConfig = TenantUtils.executeIgnore(() ->
                        platformConfigService.getPlatformConfigByCode(AMAZON_PLATFORM_CODE)
                    );
                    lastCacheTime = System.currentTimeMillis();
                }
            }
        }
        return cachedConfig;
    }

    /**
     * 刷新配置缓存
     */
    public void refreshCache() {
        synchronized (this) {
            cachedConfig = null;
            lastCacheTime = 0;
        }
        log.info("Amazon平台配置缓存已刷新");
    }

    /**
     * 获取Amazon API基础URL
     *
     * @param region 区域代码
     * @return API基础URL
     */
    public String getApiBaseUrl(String region) {
        PlatformConfigDO config = getAmazonConfig();
        if (config == null) {
            log.warn("Amazon平台配置不存在");
            return getDefaultApiBaseUrl(region);
        }
        
        String apiBaseUrl = config.getApiBaseUrl();
        if (apiBaseUrl == null || apiBaseUrl.trim().isEmpty()) {
            return getDefaultApiBaseUrl(region);
        }
        
        return apiBaseUrl;
    }

    /**
     * 获取默认的API基础URL
     *
     * @param region 区域代码
     * @return 默认API基础URL
     */
    private String getDefaultApiBaseUrl(String region) {
        switch (region.toUpperCase()) {
            case "NA":
                return "https://sellingpartnerapi-na.amazon.com";
            case "EU":
                return "https://sellingpartnerapi-eu.amazon.com";
            case "FE":
                return "https://sellingpartnerapi-fe.amazon.com";
            default:
                return "https://sellingpartnerapi-na.amazon.com";
        }
    }

    /**
     * 获取Amazon认证配置
     *
     * @return 认证配置JSON
     */
    public String getAuthConfig() {
        PlatformConfigDO config = getAmazonConfig();
        return config != null ? config.getAuthConfig() : null;
    }

    /**
     * 获取Amazon频率限制配置
     *
     * @return 频率限制配置JSON
     */
    public String getRateLimitConfig() {
        PlatformConfigDO config = getAmazonConfig();
        return config != null ? config.getRateLimitConfig() : null;
    }

    /**
     * 检查Amazon平台是否启用
     *
     * @return 是否启用
     */
    public boolean isEnabled() {
        PlatformConfigDO config = getAmazonConfig();
        return config != null && config.getEnabled() != null && config.getEnabled();
    }

    /**
     * 获取Webhook配置
     *
     * @return Webhook配置
     */
    public Map<String, Object> getWebhookConfig() {
        PlatformConfigDO config = getAmazonConfig();
        if (config == null || config.getWebhookConfig() == null) {
            return new HashMap<>();
        }

        try {
            return objectMapper.readValue(config.getWebhookConfig(),
                new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            log.error("解析Webhook配置失败", e);
            return new HashMap<>();
        }
    }

    /**
     * 获取同步配置
     *
     * @return 同步配置
     */
    public Map<String, Object> getSyncConfig() {
        PlatformConfigDO config = getAmazonConfig();
        if (config == null || config.getSyncConfig() == null) {
            return getDefaultSyncConfig();
        }

        try {
            return objectMapper.readValue(config.getSyncConfig(),
                new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            log.error("解析同步配置失败", e);
            return getDefaultSyncConfig();
        }
    }

    /**
     * 获取费率配置
     *
     * @return 费率配置
     */
    public Map<String, Object> getFeeConfig() {
        PlatformConfigDO config = getAmazonConfig();
        if (config == null || config.getFeeConfig() == null) {
            return new HashMap<>();
        }

        try {
            return objectMapper.readValue(config.getFeeConfig(),
                new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            log.error("解析费率配置失败", e);
            return new HashMap<>();
        }
    }

    /**
     * 获取支持的功能特性
     *
     * @return 功能特性列表
     */
    public Map<String, Object> getFeatures() {
        PlatformConfigDO config = getAmazonConfig();
        if (config == null || config.getFeatures() == null) {
            return getDefaultFeatures();
        }

        try {
            return objectMapper.readValue(config.getFeatures(),
                new TypeReference<Map<String, Object>>() {});
        } catch (Exception e) {
            log.error("解析功能特性失败", e);
            return getDefaultFeatures();
        }
    }

    /**
     * 获取支持的货币列表
     *
     * @return 货币代码数组
     */
    public String[] getSupportedCurrencies() {
        PlatformConfigDO config = getAmazonConfig();
        if (config == null || config.getSupportedCurrencies() == null) {
            return new String[]{"USD", "EUR", "GBP", "JPY", "CAD", "AUD"};
        }

        return config.getSupportedCurrencies().split(",");
    }

    /**
     * 获取支持的语言列表
     *
     * @return 语言代码数组
     */
    public String[] getSupportedLanguages() {
        PlatformConfigDO config = getAmazonConfig();
        if (config == null || config.getSupportedLanguages() == null) {
            return new String[]{"en", "es", "fr", "de", "it", "ja", "zh"};
        }

        return config.getSupportedLanguages().split(",");
    }

    // ==================== 私有方法 ====================

    /**
     * 创建默认Amazon配置
     */
    private void createDefaultAmazonConfig() {
        try {
            // TODO: 实现创建默认Amazon配置的逻辑
            // 这里需要创建PlatformConfigSaveReqVO并调用platformConfigService.createPlatformConfig
            log.info("创建默认Amazon配置完成");
        } catch (Exception e) {
            log.error("创建默认Amazon配置失败", e);
        }
    }

    /**
     * 获取默认同步配置
     */
    private Map<String, Object> getDefaultSyncConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("orderSyncInterval", 30); // 订单同步间隔（分钟）
        config.put("productSyncInterval", 60); // 商品同步间隔（分钟）
        config.put("inventorySyncInterval", 15); // 库存同步间隔（分钟）
        config.put("batchSize", 50); // 批次大小
        config.put("maxRetryCount", 3); // 最大重试次数
        config.put("autoSync", true); // 是否自动同步
        return config;
    }

    /**
     * 获取默认功能特性
     */
    private Map<String, Object> getDefaultFeatures() {
        Map<String, Object> features = new HashMap<>();
        features.put("orderSync", true); // 订单同步
        features.put("productSync", true); // 商品同步
        features.put("inventorySync", true); // 库存同步
        features.put("priceSync", true); // 价格同步
        features.put("webhookSupport", true); // Webhook支持
        features.put("bulkOperations", true); // 批量操作
        features.put("realTimeSync", false); // 实时同步
        features.put("advancedReporting", true); // 高级报告
        return features;
    }

}
